package com.iflytek.rule.strategy.resultdata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import com.iflytek.rule.cache.RedisConfig;
import com.iflytek.rule.cache.RedisUtils;
import com.iflytek.rule.model.RuleResultModel;
import com.iflytek.rule.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @Author weibi
 * @Date 2020/3/10 15:46
 * @Version 1.0
 * @Description TODO
 **/
public class GetUpperDeptInfoResultData implements IResultData {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisConfig redisConfig;

    @Override
    public Object result(Object requestObj, Object res, String resObjPath, RuleResultModel resultModel) {
        List<Object> list = (List) Utils.rpcResult(res, resObjPath, resultModel);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        // 过滤重复
        list = list.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> String.valueOf(ReflectUtil.getFieldValue(o, "parentDeptid"))))), ArrayList::new));

        // 入缓存
        if (!CollectionUtil.isEmpty(list)) {
            String key = Utils.setRedisKey(
                    resultModel.getMerchant(),
                    "getUpperDeptInfo",
                    "depts"
            );
            redisUtils.lSet(key, list, redisConfig.getTimeout().get("depts"));
        }

        return list;
    }
}
